const jwt = require('jsonwebtoken')
const { createUser, getUserInfo, updateById } = require('../service/user.service')
const { userRegisterError } = require('../constant/err.type')
const { JWT_SECRET } = require("../config/config.default.js")
class UserController {
    async register(ctx, next) {
        // 获取数据
        const { user_name, password } = ctx.request.body;
        // 操作数据库
        try {
            const res = await createUser(user_name, password)
            //    返回结果
            ctx.body = {
                code: '200',
                message: '用户注册成功',
                result: {
                    id: res.id,
                    user_name: res.user_name
                }
            }
        } catch (err) {
            console.log(err)
            ctx.app.emit('error', userRegisterError, ctx)
        }

    }
    // 登录
    async login(ctx, next) {
        const { user_name } = ctx.request.body;
        ctx.body = `欢迎回来，${user_name}!`
        console.log("user_name", user_name)
        // 1、获取用户信息在token的playload中,记录id，user_name，is_admin
        try {
            // 剔除password熟悉将剩余属性放入res中
            const { password, ...res } = await getUserInfo({ user_name })
            console.log("res", res)
            ctx.body = {
                code: '200',
                message: '登录成功',
                result: {
                    token: jwt.sign(res, JWT_SECRET, { expiresIn: '1d' })
                }
            }
        } catch (err) {
            console.error('用户登录失败', err)
        }
    }
    // 修改密码
    async changePassword(ctx, next) {
        // 1、获取数据
        const id = ctx.state.user.id;
        const password = ctx.request.body.password
        // console.log(id, password);
        // 2、操作数据库
        if (await updateById({ id, password })) {
            ctx.body = {
                code: '200',
                message: '修改密码成功',
                result: ''
            }
        } else {
            ctx.body = {
                code: '10007',
                message: '修改密码失败',
                result: ''
            }
        }
        // 3、返回结果
    }
}

module.exports = new UserController();